import axios from 'axios'
import { Notification,MessageBox,Message } from 'element-ui'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
//创建一个axios实例
const Service = axios.create({
	baseURL:process.env.KERNEL,
	timeout:60000 //设置请求超时时间6s
})

//请求拦截
axios.interceptors.request.use(config => {
	if(config) {
		config.headers['Authorizetion'] = localStorage.getItem('token')
		return config
	} else {
		//如取消请求
		return Promise.reject()
	}
},error => {
	Promise.reject()
})

//响应拦截
Service.interceptors.response.use(res => {
	const code = res.data.code  || 200
	const msg = res.data.msg
	if(code == 401){
		Message({
			message:msg,
			type:'error'
		})
	} else if(code == 500) {
		Message({
			message:msg,
			type:'error'
		})
		return Promise.reject(new Error(msg))
	} else if(code != 200) {
		Notification.error({
			title:msg
		})
		return Promise.reject('error')
	} else {
		return res.data
	}
},error => {
	// 判断error的status 代码，并将对应的信息告知用户
	return Promise.reject(error)
})

export default Service
